package boardgamer.yavalath.client.replaylobby;

import android.os.AsyncTask;
import android.os.Environment;
import boardgamer.yavalath.common.YavalathReplay;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Map;

import static android.os.Environment.MEDIA_MOUNTED;
import static boardgamer.yavalath.client.YavalathReplaySaver.EXTENSION;
import static boardgamer.yavalath.client.YavalathReplaySaver.ROOT_DIRECTORY;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public class YavalathReplayLoader {
  
  public void load(LoadReplayCallback callback) {
    new LoadReplayTask(callback).execute((Void)null);
  }

  public static interface LoadReplayCallback {

    void loadComplete(Map<String, YavalathReplay> replays);
  }

  private static class LoadReplayTask extends AsyncTask<Void, Void, Map<String, YavalathReplay>> {
    
    private final LoadReplayCallback callback;
    
    public LoadReplayTask(LoadReplayCallback callback) {
      this.callback = checkNotNull(callback, "callback");
    }

    @Override
    protected Map<String, YavalathReplay> doInBackground(Void... voids) {
      Map<String, YavalathReplay> replays = Maps.newHashMap();
      if (Environment.getExternalStorageState().equals(MEDIA_MOUNTED)) {
        File root = Environment.getExternalStoragePublicDirectory(ROOT_DIRECTORY);

        String[] fileNames = root.list(new FilenameFilter() {
          @Override
          public boolean accept(File file, String s) {
            return s.endsWith(EXTENSION);
          }
        });

        for (String fileName : fileNames) {
          FileInputStream fileInputStream = null;
          try {
            File fullFileName = new File(root, fileName);
            fileInputStream = new FileInputStream(fullFileName);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Object loadedObject = objectInputStream.readObject();
            if (loadedObject instanceof YavalathReplay) {
              replays.put(
                  fileName.substring(0, fileName.length() - EXTENSION.length()),
                  (YavalathReplay) loadedObject);
            }
          } catch (IOException exception) {
            int a = 0;
          } catch (ClassNotFoundException exception) {
          } finally {
            try {
              fileInputStream.close();
            } catch (IOException e) { }
          }
        }
      }

      return ImmutableMap.copyOf(replays);
    }

    @Override
    protected void onPostExecute(Map<String, YavalathReplay> replays) {
      callback.loadComplete(replays);
    }
  }
}
